import axios from 'axios'
import config from '../config/config.js'

const instance = axios.create({
  baseURL: config.axiosBaseURL,
  timeout: 10000,
})

instance.interceptors.response.use(
  (response) => {
    if (response.status >= 200 && response.status < 300) {
      return response
    } else {
      console.warn('Request succeeded with non-2xx status:', response.status)
      return Promise.reject(response)
    }
  },
  async (error) => {
    const config = error.config;

    // If the retry count is undefined, set it to 0
    if (!config._retryCount) {
      config._retryCount = 0;
    }

     // Set a limit for retries
     const RETRY_LIMIT = 5;

     // If retry count is less than the limit, try the request again
    if (config._retryCount < RETRY_LIMIT) {
      config._retryCount += 1;

      // Add a slight delay before retrying
      await new Promise((resolve) => setTimeout(resolve, 500));

      // Retry the request
      console.log('Retry the request', config._retryCount);
      return instance(config);
    }

    // If all retries fail, return the error
    if (error.response) {
      console.error('Error status:', error.response.status)
      console.error('Error data:', error.response.data)
    } else if (error.request) {
      console.error('No response received:', error.request)
    } else {
      console.error('Error message:', error.message)
    }
    return Promise.reject(new Error('The request failed, please try again later.'))
  }
)

export default instance
